package com.stormkai.controller;


import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.stormkai.error.BusinessException;
import com.stormkai.error.CommonError;
import com.stormkai.error.EnumBusinessError;
import com.stormkai.response.CommonReturnType;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class BaseController {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request,Exception ex){

        CommonReturnType returnType = new CommonReturnType();
        Map<String,Object> map = new HashMap<>();

        if (ex instanceof BusinessException){ //返回业务异常信息

            //从业务异常中取出错误代码和错误消息
            map.put("errCode",((BusinessException)ex).getErrorCode());
            map.put("errMsg",((BusinessException) ex).getErrorMsg());
            return  CommonReturnType.create(map,CommonError.STATUS_FAILED);

        }else { //系统的其他异常不要暴露给用户
            map.put("errCode", EnumBusinessError.UNKONWN_ERROR.getErrorCode());
            map.put("errMsg",EnumBusinessError.UNKONWN_ERROR.getErrorMsg());
            map.put("exception",ex.getCause());
            ex.printStackTrace();
            return CommonReturnType.create(map,CommonError.STATUS_FAILED);
        }
    }
}
